package com.hcc.flow.server.service.sys;

import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hcc.flow.server.common.model.ApiResult;
import com.hcc.flow.server.common.utils.StringUtilsV2;
import com.hcc.flow.server.common.utils.TokenUtil;
import com.hcc.flow.server.dao.sys.RoleDao;
import com.hcc.flow.server.dto.sys.RoleDto;
import com.hcc.flow.server.model.common.LoginUser;
import com.hcc.flow.server.model.sys.Role;
import com.hcc.flow.server.utils.CheckIdUtil;
import com.hcc.flow.server.utils.UserUtil;
import com.hcc.flow.server.vo.sys.RoleVO;
import com.hcc.flow.server.where.sys.RoleWhere;

@Service
public class RoleService {

	private static final Logger log = LoggerFactory.getLogger("adminLogger");

	@Autowired
	private RoleDao roleDao;
	@Autowired
	private TokenService tokenService;
	
	@Transactional
	public ApiResult<?> saveRole(RoleDto roleDto) {
		Role role = roleDto;
		List<String> permissionIds = roleDto.getPermissionIds();
		permissionIds.remove("0");
		LoginUser loginUser = UserUtil.getLoginUser();
		if (StringUtilsV2.isNotBlank(role.getRoleId())) {// 修改
			//系统数据检测
			ApiResult<?> checkAr = CheckIdUtil.checkId(Arrays.asList("1","2","3"), role.getRoleId());
			if(!checkAr.isSuccess()){
				return checkAr;
			}
			role.setUpdateUserId(loginUser.getUserId());
			updateRole(role, permissionIds);
			//角色归属机构是登录机构并且是登录用户的角色-刷新用户缓存
            if(loginUser.getOrgId().equals(roleDto.getOrgId()) && Arrays.asList(loginUser.getRoldIds().split(",")).contains(role.getRoleId())) {
            	tokenService.refresh(loginUser,true,TokenUtil.getSysId(null));
            }
		} else {// 新增
			
			role.setCreateUserId(loginUser.getUserId());
			role.setCreateOrgId(loginUser.getOrgId());
			saveRole(role, permissionIds);
		}
		return ApiResult.ok();
	}

	private void saveRole(Role role, List<String> permissionIds) {
		/*
		 * Role r = roleDao.getRole(role.getRoleName()); if (r != null) { throw
		 * new IllegalArgumentException(role.getRoleName() + "已存在"); }
		 */

		roleDao.save(role);
		if (!CollectionUtils.isEmpty(permissionIds)) {
			roleDao.saveRolePermission(role.getRoleId(), permissionIds);
		}
		log.debug("新增角色{}", role.getRoleName());
	}

	private void updateRole(Role role, List<String> permissionIds) {
		/*
		 * Role r = roleDao.getRole(role.getRoleName()); if (r != null &&
		 * r.getRoleId() != role.getRoleId()) { throw new
		 * IllegalArgumentException(role.getRoleName() + "已存在"); }
		 */

		roleDao.update(role);

		roleDao.deleteRolePermission(role.getRoleId());
		if (!CollectionUtils.isEmpty(permissionIds)) {
			roleDao.saveRolePermission(role.getRoleId(), permissionIds);
		}
		log.debug("修改角色{}", role.getRoleName());
	}

	
	@Transactional
	public void deleteRole(String id) {
		roleDao.deleteRolePermission(id);
		roleDao.deleteRoleUser(id);
		roleDao.delete(id);

		log.debug("删除角色ID: {}", id);
	}

	
	public PageInfo<RoleVO> findAllRoles(RoleWhere ewhere) {
		PageHelper.startPage(ewhere.getOffset(), ewhere.getLimit());
		if (ewhere.getSqlOrder() == null || ewhere.getSqlOrder().isEmpty()) {
			ewhere.setSqlOrder("o.create_time,t.level,t.create_time desc ");
		}
		PageHelper.orderBy(ewhere.getSqlOrder());
		List<RoleVO> log = roleDao.RoleList(ewhere);
		PageInfo<RoleVO> result = new PageInfo<RoleVO>(log);
		return result;
	}

}
